<?php

namespace App\Http\Controllers\Img;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Validator;

class VideoController extends Controller
{

    public function ProductVideo(Request $request)
    {
        //  var_dump($_FILES['video']);
        // //  echo '文件大小'.filesize($_FILES['video']);
        //  echo '----------------------';
        //  echo '<br />';
        //  var_dump($_FILES['img']);
        $validator = Validator::make($request->all(), [
            'video' => 'required',
            'u_id' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 401);
        }
        if (!file_exists('./temp/product/videos')) {

            mkdir('./temp/product/videos/');
        }
        $temp = explode('.', $_FILES['video']['name']);
        $extension = end($temp);
        $allowedExts = array('avi', 'mpg', 'mpeg', 'rm', 'mp4', 'rmvb', 'dat', 'wmv', 'mov', 'asf', 'divx', 'mpe', 'mkv', 'vob');
        if (($_FILES['video']['size'] < 52428800)
            && in_array($extension, $allowedExts)) {
            if ($_FILES['video']['error'] > 0) {
                session()->flash('false', '视频错误!');
                $data = ['success' => false, 'message' => '视频错误'];
                return json_encode($data);
            } else {
                $picname = $_FILES['video']['name'];
                $first_dir = './temp/' . $request->u_id . '/';
                $secend_dir = './temp/' . $request->u_id . '/product/';
                $url = './temp/' . $request->u_id . '/product/videos/' . $picname;
                $third_dir = './temp/' . $request->u_id . '/product/videos/';
                if (!is_dir($first_dir)) {
                    mkdir($first_dir, 0777);
                }
                if (!is_dir($secend_dir)) {
                    mkdir($secend_dir, 0777);
                }
                if (!is_dir($third_dir)) {
                    mkdir($third_dir, 0777);
                }
                if (!file_exists($url)) {
                    $counter_file = $url;
                    $fopen = fopen($counter_file, 'wb'); //新建文件命令
                    fclose($fopen);
                }
                move_uploaded_file($_FILES['video']['tmp_name'], $url);
                $data = ['success' => true, 'message' => '上传成功', 'url' => $url, 'invokeResultCode' => 200];
                return json_encode($data);
            }
        } else {
            session()->flash('false', '格式错误!');
            $data = ['success' => false, 'message' => '格式错误'];
            return json_encode($data);
        }
    }
}
